// The NSpring Framework for .NET
// Copyright (c) 2003, Jeffrey Varszegi
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without modification, 
// are permitted provided that the following conditions are met:
// 
// - Redistributions of source code must retain the above copyright notice, this 
// list of conditions and the following disclaimer.
// 
// - Redistributions in binary form must reproduce the above copyright notice, this 
// list of conditions and the following disclaimer in the documentation and/or other 
// materials provided with the distribution.
// 
// - Neither the name of the NSpring project nor the names of its contributors may 
// be used to endorse or promote products derived from this software without 
// specific prior written permission from the copyright owner.
// 
// - No product derived from this software may be called "NSpring", nor may 
// "NSpring" appear in the name of such a product, without specific prior written 
// permission from the copyright owner.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
// OF THE POSSIBILITY OF SUCH DAMAGE. 

namespace NSpring.Logging {

using System;
using System.Collections;
using System.IO;
using System.Text;

using Common;

/// <summary>
/// Each EventFormatter subclass provides formatting logic for Event instances created
/// by loggers in response to calls to their Log() methods.  Built-in formatting classes,
/// including SimpleEventFormatter and XMLEventFormatter, occur in the NSpring.Logging.EventFormatters
/// namespace.  Third parties (this means you) are also free to implement EventFormatter 
/// subclasses and set them on Logger instances, providing an easy way to extend the formatting
/// functionality of the logging package.
/// </summary>
public abstract class EventFormatter {
    private Logger logger                               = null;

    protected Encoding encoding                         = Encoding.UTF8;
    
    protected DataFormatter dataFormatter;
    
    protected string prefix                             = null;
    protected string suffix                             = null;

    protected object monitor                            = new object();
    
    /// <summary>
    /// Sets the data formatter used by this instance.  The passed-in value is copied before being
    /// stored, meaning that no future modifications of the external object will have effect on the 
    /// output of this instance (unless this property is set again)
    /// </summary>
    public DataFormatter DataFormatter {
        set {
            if (value == null) {
                throw new ArgumentNullException();
            }
            DataFormatter copy = value.Copy();
            lock (monitor) {
                if (UpdateDataFormatter(copy)) {
                    dataFormatter = copy;
                }
                else {
                    throw new ArgumentException("Invalid data formatter");
                }
            }
        }
        get {
            return dataFormatter;
        }
    }

    public string Prefix {
        get {
            return prefix;
        }
        set {
            lock (monitor) {
                if (UpdatePrefix(value)) {
                    prefix = value;
                }
                else {
                    throw new ApplicationException("Invalid operation");
                }
            }
        }
    }
    
    protected virtual bool UpdatePrefix(string _newPrefix) {
        return true;
    }
    
    public string Suffix {
        get {
            return suffix;
        }
        set {
            lock (monitor) {
                if (UpdateSuffix(value)) {
                    suffix = value;
                }
                else {
                    throw new ApplicationException("Invalid operation");
                }
            }
        }
    }
    
    protected virtual bool UpdateSuffix(string _newSuffix) {
        return true;
    }
    
    /// <summary>
    /// Provides a notification hook for subclasses to perform implementation-specific logic
    /// when data formatters are set, and to control which types of data formatters may be used
    /// with them
    /// </summary>
    /// <param name="_dataFormatter">The data formatter to check</param>
    /// <returns>true if the subclass accepts the data formatter, false otherwise</returns>
    protected virtual bool UpdateDataFormatter(DataFormatter _newDataFormatter) {
        return true;
    }

    /// <summary>
    /// Provides implementation-specific logic for formatting Event objects
    /// </summary>
    /// <param name="_event">The NSpring.Logging.Event instance to format</param>
    /// <returns>A string representation of the specified Event</returns>
    public abstract string Format(Event _event);
    
    /// <summary>
    /// In certain situations (such as logging many records to a stream as XML) it is desirable
    /// to write a header and footer before and after the contents.  This method provides the header
    /// for such situations
    /// </summary>
    /// <returns>A string with which to begin a list of formatted Events</returns>
    public virtual string GetEventListHeader() {
        return null;
    }
    
    /// <summary>
    /// In certain situations (such as logging many records to a stream as XML) it is desirable
    /// to write a header and footer before and after the contents.  This method provides the footer
    /// for such situations
    /// </summary>
    /// <returns>A string with which to end a list of formatted Events</returns>
    public virtual string GetEventListFooter() {
        return null;
    }
    
    public virtual void Initialize() {}
    
    /// <summary>
    /// Gets and sets encoding used to format Event objects
    /// </summary>
    public Encoding Encoding {
        get {
            return encoding;
        }
        set {
            if (value == null) {
                throw new ArgumentNullException();
            }
            lock (monitor) {
                if (!UpdateEncoding(value)) {
                    throw new ArgumentException("Invalid encoding");
                }
                dataFormatter.Encoding = encoding;
                encoding = value;
                dataFormatter.Encoding = encoding;
            }
        }
    }
    
    protected virtual bool UpdateEncoding(Encoding _newEncoding) {
        return true;
    }

    /// <summary>
    /// Sets the logger that uses this instance.  Used to ensure that an event formatter
    /// belongs to only one logger, in order to reduce lock contention
    /// </summary>
    public Logger Logger {
        set {
            lock (monitor) {
                if (value == null) {
                    return;
                }
                if (logger != null) {
                    throw new InvalidOperationException("An EventFormatter instance can only be used with one logger.  (Try using Copy() to create a deep copy)");
                }
                logger = value;
            }
        }
    }
    
    private static string timeZone                          = Constants.ISO_8601_TIME_ZONE;
    private static string daylightSavingsTimeZone           = Constants.ISO_8601_DAYLIGHT_SAVINGS_TIME_ZONE;
    protected static string GetLocalTimeZone(int month, int day) {
        switch (month) {
            case 1       :
            case 2       :
            case 3       : {
                return daylightSavingsTimeZone;
            }
            case 4       : {
                if (day > 2) {
                    return timeZone;
                }
                else {
                    return daylightSavingsTimeZone;
                }
            }
            case 5       :
            case 6       :
            case 7       :
            case 8       :
            case 9       : {
                return timeZone;
            }
            case 10      : {
                if (day < 30) {
                    return timeZone;
                }
                else {
                    return daylightSavingsTimeZone;
                }
            }
            case 11      :
            case 12      : {
                return daylightSavingsTimeZone;
            }
            default      : {
                return timeZone;
            }
        }
    }
    
}

}
